<?php
namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\Dashboard;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;

use App\Models\ActivityModel;
use App\Models\Area;
use App\Models\EMail;

use Encore\Admin\Grid;
use Encore\Admin\Form;
use App\Admin\Extra\Search\Html;
use \Illuminate\Support\Facades\Input;

class ActivityController extends Controller
{
    public function index()
    {
        return Admin::content(function (Content $content) {
            $content->header('Activity Manager List');
            $act_type = \Request::get('act_type') ?: \Request::get('event_id');
            $area = \Request::get('area');
            $content->row(Html::append([
                Html::likeRedirect('act_name', 'Activity Manager', url()->current()),
                Html::button('GO', url()->current(), 'search-filter'),
                $area ? Html::button('Clear Game Action', '/admin/activity/sync-game?area='.$area.'&operator=del_all&act_type='.$act_type, 'confirm-ajax btn-danger') : '',
                Html::sjs(url()->current()),
            ]));
            
            // 根据不同的活动类型显示不同的列表格式
            $act_type = Input::get('act_type', 201);
            switch ($act_type) {
                case 201:
                $grid = $this->type_email_list($content);
                break;
            }

            $grid && $content->row($grid->render());
        });
    }

    // 事件列表
    public function anyEventList(){
        return Admin::content(function(Content $content) {
            $content->header('Activity Event List Manager.');

            $list = ActivityModel::getEventList();
            
            $row_num = 5;
            $pointer = count($list);
            $row_btn = [];
            foreach ($list as $event_id => $event_obj) {

                $pointer--;
                $class = $event_obj[2] ? 'btn-info btn-goto' : 'btn-default';
                $row_btn[] = Html::button($event_obj[1], '/admin/activity/list?event_id='.$event_id, ' btn-200  '. $class);

                if ( (($pointer % $row_num == 0) || $pointer <=0 ) && count($row_btn) ) {
                    $content->row(Html::append($row_btn ) );
                    $row_btn = [];
                }
            }
        });
    }


    // ========================= 保护性 方法 ============================= //
    // 邮件列表方法
    protected function type_email_list($content)
    {
        $content->description('activity list');
        $grid = Admin::grid(ActivityModel::class, function(Grid $grid){
            //$grid->model()->where('deleted_at', 0);//
            $area_data = Area::areaSelectData(0);
            // $event_list = ActivityModel::getEventList();
            $act_type_option = ActivityModel::getEventListOption();
            $grid->actions(function($actions)use(&$row){
                $row = $actions->row;
                $actions->disableEdit();
                $actions->disableDelete();
                $actions->append(Html::button('view', '/admin/activity/show?id='.$row->id, 'btn-goto btn-xs'));
                $actions->append(' ' . Html::button('EDIT', '/admin/activity/edit?id='.$row->id, 'btn-goto btn-xs'));
                $actions->append(' '.Html::button('DEL', '/admin/activity/api-delete?_id='.$actions->getKey().'&deleted_at=1', 'confirm-ajax btn-danger btn-xs btn-clear'));
                $actions->append(' ');
                // 如果未选择大区 全部显示 unknow
                $actions->append( !\Request::get('area')?'unknow':( $row->active == 1 ? Html::button('close', '/admin/activity/sync-game?operator=del&_id='.$row->id, 'confirm-ajax btn-xs btn-danger')
                : Html::button('open', '/admin/activity/sync-game?operator=save&_id='.$row->id, 'confirm-ajax btn-xs btn-success')));
            });

            // 字段类型
            $grid->id('ID')->sortable();
            $grid->act_id('Act Id');
            $grid->act_name('Act Name');
            $grid->act_type('Activity Type')->display(function($value) use($act_type_option) {
                return $act_type_option[$value];
            });
            $grid->area('Server')->display(function($value) use( $area_data) {
                $req = ['act_type' => \Request::get('event_id'), 'area' => $value];
                return '<a href = "'.\App\Service\Common::build_url_query(url()->current(),$req).'">' . $area_data[$value] .'</a>';
            });
            $grid->active('Activity State')->display(function($state) {
                $html = $state == 1 ?'<span class="label label-success">On</span>' : '<span class="badge">Off</span>';
                return $html ;
            });
            $grid->disableCreateButton();

            $grid->tools(function ($tools)use($artworkid) {
                $tools->append(Html::button('new', '/admin/activity/create', 'btn-goto btn-sm btn-success ', 'float:right;'));

            });
            $grid->filter(function ($filter) use ($area_data) {

                $filter->equal('act_id', 'Act Id')->placeholder('Act Id');
                $filter->equal('act_name', 'Act Name')->placeholder('Acitivity Name');
                
                $filter->equal('area', 'Area')->select($area_data);

                $filter->disableIdFilter();
            });

        });
        return $grid;
    }

    public function anyEdit(){
        $id = Input::get('id');
        $clone = Input::get('clone');

        $one = ActivityModel::find($id) ?: new ActivityModel;
        ActivityModel::conv_2_object($one);

        $data['one'] = $one;
        $data['clone'] = $clone;
        $data['act_type_option'] = ActivityModel::getEventListOption();

        
        return Admin::content(function($content) use($data){
		    $content->header('Activity Edit');
            $grid = Admin::Form(\App\Models\ActivityModel::class, function(Form $form)use($data){
                $one = $data['one'];
                //$one->area_list = explode(',', $one->area_list);
                // $form->html('aaaaaaaaaaaaaa');
                $form->text('act_id', 'act_id')->default($one->act_id);
                $form->text('act_name', 'act_name')->default($one->act_name);
                $form->select('area', 'area')->options(Area::areaSelectData(0))->default($one->area);
                $form->select('act_type', 'Act Type')->options($data['act_type_option'])->default($one->act_type);
                // $form->textarea('', 'content')->default($one->content);
                $form->select('cond', 'Condition')->options($data['act_type_option'])->default($one->cond);
                
                $form->text('act_object[title]', 'Email Title')->default($one->act_object['title']);
                $form->textarea('act_object[content]', 'Email Content')->default($one->act_object['content']);
                $form->html(\App\Admin\Extra\Form\TForm::mutilSelectItem('item_list', $one->item_list?:[], 'attach', '/admin/mail/item-all'), 'Reward List');            
                                
                if (!$data['clone']) {
                    $form->hidden('_id', 'id')->default($one->id);
                }

                $form->saved(function (Form $form) {
                    \Log::debug(json_encode(['data'=>'save click']));
                    admin_toastr('laravel-admin ','success');
                    return response('success');
                });

                $form->disablePjax();
                $form->setAction('/admin/activity/api-save/');

            });
            $content->row($grid);
        });
      
    }
    // 显示活动详情
    public function anyShow()
    {

    }
    public function anyAdd()
    {
        return $this->anyEdit();
    }

    public function anyApiSave(){
        $data = Input::all();

        $url = url()->to("/admin/activity/index");
        
        $one = ActivityModel::find($data['_id']) ? : new ActivityModel();

        $ret = ActivityModel::assignByOut($one, $data);
        if ( $ret) {
            echo json_encode(['code' => 444, 'msg' => admin_toastr('activity save param! code =' . $ret,'error'), 'data' => $data]);
            return ;
        }
        // \Log::debug('activity save', ['data'=>$one, $data]);
        if (!$one->act_id || !$one->act_type || !$one->item_list) {
            echo json_encode(['code' => 444, 'msg' => admin_toastr('activity save param!','error'), 'data' => $data]);
            return;
        }
        
        $one->save();
        
        echo json_encode(['code' => 0,'status'=>true, 'msg' => admin_toastr('activity save!','success'), 'data' =>$one->delete_at]);
        return;
    }

    public function anyApiDelete(){
        $data = Input::all();
        $one = ActivityModel::find($data['_id']);
        if ($one){
            $one->delete();
        }

        echo json_encode(['code' => 0,'status'=>true, 'msg' => admin_toastr('activity delete success!!!','success'), ]);
    }

    // 发送消息到game
    public function anySyncToGame(){
        $req_param = Input::all();
        $one = ActivityModel::find($req_param['_id']) ?: new ActivityModel;
        !$one->act_type && $one->act_type = $req_param['act_type'];
        !$one->area && $one->area = $req_param['area'];

        if (!$one->area || !$one->act_type || !$req_param['operator']) {
            echo json_encode(['code' => 444, 'msg' => admin_toastr('activity sync to game!','error'), 'data' => $one]);
            \Log::info('activity sync to game error:', [$one->area, $one->act_type, $req_param['operator']]);
            return ;
        }
        ActivityModel::syncToGame($one, $one->area, $req_param['operator']);
        echo json_encode(['code' => 0,'status'=>true, 'msg' => admin_toastr('activity sync to game success!!!','success'), ]);
    }
}